/*
 * Copyright (C) 2016, apexes.net. All rights reserved.
 * 
 *        http://www.apexes.net
 * 
 */
package net.apexes.wsonrpc.core.exception;

import net.apexes.wsonrpc.json.JsonRpcError;
import net.apexes.wsonrpc.util.JsonRpcErrors;

/**
 * 
 * @author <a href="mailto:hedyn@foxmail.com">HeDYn</a>
 *
 */
public class RemoteException extends WsonrpcRuntimeException {
    private static final long serialVersionUID = 1L;

    private final JsonRpcError error;

    protected RemoteException(String message, Throwable cause, JsonRpcError error) {
        super(message, cause);
        this.error = error;
    }

    public JsonRpcError getJsonRpcError() {
        return error;
    }

    public static RemoteException create(JsonRpcError error) {
        String message = formatMessage(error);
        Throwable cause = JsonRpcErrors.fromCause(error.getData());
        if (error.getCode() != null) {
            switch (error.getCode()) {
                case RemoteParseException.CODE:
                    return new RemoteParseException(message, cause, error);
                case RemoteInvalidRequestException.CODE:
                    return new RemoteInvalidRequestException(message, cause, error);
                case RemoteMethodNotFoundException.CODE:
                    return new RemoteMethodNotFoundException(message, cause, error);
                case RemoteInvalidParamsException.CODE:
                    return new RemoteInvalidParamsException(message, cause, error);
                case RemoteInternalException.CODE:
                    return new RemoteInternalException(message, cause, error);
                default:
                    return new RemoteServerException(message, cause, error);
            }
        }
        return new RemoteServerException(message, cause, error);
    }

    private static String formatMessage(JsonRpcError error) {
        StringBuilder str = new StringBuilder();
        if (error.getCode() != null) {
            str.append(error.getCode());
        }
        if (error.getMessage() != null) {
            if (str.length() > 0) {
                str.append(", ");
            }
            str.append(error.getMessage());
        }
        return str.toString();
    }
}
